package main

import (
	"fmt"
	"math/rand"
	"time"
)

func worker(id int, c chan int) {
	for n := range c {
		time.Sleep(time.Second)
		fmt.Printf("Worker %d received %d\n",
			id, n)
	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500))*time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

func main() {
	var c1, c2 = generator(),generator()
	var worker = createWorker(0)
	var values []int

	tm := time.After(10*time.Second)
	tick := time.Tick(time.Second)

	for {
		var activeworkers chan<-int
		var activevalue int
		if len(values)>0 {
			activeworkers = worker
			activevalue = values[0]
		}
		select {
		case n := <-c1:
			fmt.Println("Received in c1 :", n)
			values = append(values,n)
		case n := <-c2:
			fmt.Println("Received in c2 :", n)
			values = append(values,n)
		case activeworkers <- activevalue:
			values = values[1:]
		case <-time.After(800*time.Millisecond):
			fmt.Println("timeout")
		case <-tick:
			fmt.Println("values len :",len(values))
		case <-tm:
			fmt.Println("bye!")
			return


		}
	}

}
